package com.data.modules.system.util.itext;

import com.itextpdf.text.pdf.BaseFont;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;

@Slf4j
public final class HtmlUtil {

    private HtmlUtil() {
    }
    // 字体路径，放在资源目录下
    private static final String FONT_PATH = "/font/simsun.ttc";

    public static void file2Pdf(File htmlFile, String pdfFile,String fontPath) {
        try (OutputStream os = new FileOutputStream(pdfFile)) {
            String url = htmlFile.toURI().toURL().toString();
            ITextRenderer renderer = new ITextRenderer();
            renderer.setDocument(url);
            // 解决中文支持
            ITextFontResolver fontResolver = renderer.getFontResolver();
            /*//word模板地址获取方式二：优点---相比上一种方式，这种方法不会在linux或者jar上失效
            ClassPathResource classPathResource = new ClassPathResource(FONT_PATH);
            String fontPath = classPathResource.getURL().getPath();*/
            // 获取字体绝对路径，ApplicationContextUtil是我自己写的类
            //String fontPath = ApplicationContextUtil.classpath(FONT_PATH);
            fontResolver.addFont(fontPath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
            renderer.layout();
            renderer.createPDF(os);
        } catch (Exception e) {
            // 抛出自定义异常
            e.printStackTrace();
        }
    }

    public static void html2Pdf(String html, String pdfFile,String fontPath) {
        String pdfDir = StringUtils.substringBeforeLast(pdfFile, "/");
        File file = new File(pdfDir);
        if (!file.exists()) {
            file.mkdirs();
        }
        try (OutputStream os = new FileOutputStream(pdfFile)) {
            ITextRenderer renderer = new ITextRenderer();
            renderer.setDocumentFromString(html);
            // 解决中文支持
            ITextFontResolver fontResolver = renderer.getFontResolver();
            /*ClassPathResource classPathResource = new ClassPathResource(FONT_PATH);
            String fontPath = classPathResource.getURL().getPath();*/
            // 获取字体绝对路径，ApplicationContextUtil是我自己写的类
            //String fontPath = ApplicationContextUtil.classpath(FONT_PATH);
            fontResolver.addFont(fontPath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
            renderer.layout();
            renderer.createPDF(os);
        } catch (Exception e) {
            // 抛出自定义异常
            e.printStackTrace();
        }
    }
}
